package com.dgut.doctorservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dgut.commonutils.DateHandler;
import com.dgut.commonutils.Result;
import com.dgut.doctorservice.entity.DepartmentInfo;
import com.dgut.doctorservice.entity.Doctor;
import com.dgut.doctorservice.entity.vo.DoctorQuery;
import com.dgut.doctorservice.service.DepartmentInfoService;
import com.dgut.doctorservice.service.DoctorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dgut
 * @since 2021-09-01
 */
@RestController
@RequestMapping("/doctorservice/doctor")
@Api("医生控制器")
@CrossOrigin
public class DoctorController {

    @Autowired
    private DoctorService doctorService;

    @Autowired
    private DepartmentInfoService service;

    @ApiOperation("根据二级科室获取医生")
    @GetMapping("getDoctorsByDepartmentId/{id}")
    public Result getDoctorsByDepartmentId(@PathVariable("id")String id){
        QueryWrapper<Doctor> wrapper = new QueryWrapper<>();
        wrapper.eq("department_id",id);
        List<Doctor> list = doctorService.list(wrapper);
        if (list.size()==0){
            return Result.succ().message("该二级科室暂时没有医生");
        }
        return Result.succ().data("list",list);
    }


    @ApiOperation("将所有医生的信息导出到excel文件")
    @GetMapping("exportDoctorsInfo")
    public void exportDoctorsInfo(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        String date= DateHandler.getStringOfDate();
        HSSFSheet sheet = workbook.createSheet(date + "未打卡名单");

        final List<Doctor> allDoctors; //要导出的数据
        allDoctors= doctorService.list();

        // 设置要导出的文件的名字
        String fileName = "AllDoctors" + ".xls";

        // 新增数据行，并且设置单元格数据
        int rowNum = 1;

        // headers表示excel表中第一行的表头 在excel表中添加表头
        String[] headers = {"序号","医生ID","姓名", "简介","资历","医生类型","性别","身份证","电话","头像","科室"};
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (Doctor user : allDoctors) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(rowNum);
            row1.createCell(1).setCellValue(user.getId());
            row1.createCell(2).setCellValue(user.getName());
            row1.createCell(3).setCellValue(user.getInfo());
            row1.createCell(4).setCellValue(user.getCareer());
            if (user.getLevel()==1){
                row1.createCell(5).setCellValue("专家");
            }else {
                row1.createCell(5).setCellValue("普通医生");
            }
            if(user.getSex()==1){
                row1.createCell(6).setCellValue("男");
            }else {
                row1.createCell(6).setCellValue("女");
            }

            row1.createCell(7).setCellValue(user.getIdCard());
            row1.createCell(8).setCellValue(user.getPhone());
            row1.createCell(9).setCellValue(user.getAvatar());
            QueryWrapper<DepartmentInfo> wrapper=new QueryWrapper<>();
            wrapper.eq("id", user.getDepartmentId());
            DepartmentInfo one = service.getOne(wrapper);
            row1.createCell(10).setCellValue(one.getName());

            rowNum++;
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }


    //查询医生表所有数据
    @ApiOperation("查找所有医生")
    @GetMapping("findAll")
    public Result findAllDoctor(){
        List<Doctor> doctors = doctorService.list();
        List<DepartmentInfo> departmentInfos=new ArrayList<>();
        for (int i = 0; i <doctors.size() ; i++) {
            QueryWrapper<DepartmentInfo> wrapper=new QueryWrapper<>();
            wrapper.eq("id",doctors.get(i).getDepartmentId());
            DepartmentInfo one = service.getOne(wrapper);
            departmentInfos.add(one);
        }
        //异常模拟演示
        //int i=10/0;

        //手动抛出才能把异常调用
//        try{
//            int i=10/0;
//        }catch (Exception e){
//            throw new DoctorException(20001,"执行了自定义异常");
//        }

        return Result.succ().data("items",doctors).data("department",departmentInfos);
    }

    //逻辑删除医生
    @ApiOperation("逻辑删除医生")
    @DeleteMapping("{id}")
    public Result removeDoctor(@PathVariable String id){

        boolean flag = doctorService.removeById(id);
        if (flag){
            return Result.succ().message("删除医生成功");
        }else {
            return Result.fail().message("删除医生失败");
        }
    }

    @ApiOperation("使用分页方式进行医生显示")
    @GetMapping("pageDoctors/{current}/{limit}")
    public Result pageListDoctors(@PathVariable long current,@PathVariable long limit){

        Page<Doctor> page=new Page<>(current,limit);
        doctorService.page(page,null);
        long total=page.getTotal();
        List<Doctor> records = page.getRecords();
        HashMap map = new HashMap();
        map.put("total",total);
        map.put("rows",records);
        return Result.succ().data(map);

    }

    @ApiOperation("条件查询医生带分页")
    //条件查询带分页
    @PostMapping ("pageDoctorsCondition/{current}/{limit}")
    public Result pageDoctorsCondition(@PathVariable long current, @PathVariable long limit, @RequestBody(required = false) DoctorQuery doctorQuery){
        Page<Doctor> page=new Page<>(current,limit);
        QueryWrapper<Doctor> wrapper = new QueryWrapper<>();

        //多条件组合查询
        String name = doctorQuery.getName();
        Integer level = doctorQuery.getLevel();
        String begin = doctorQuery.getBegin();
        String end = doctorQuery.getEnd();
        if (!StringUtils.isEmpty(name)){
            wrapper.like("name",name);
        }
        if (!StringUtils.isEmpty(level)){
            wrapper.eq("level",level);
        }
        if (!StringUtils.isEmpty(begin)){
            wrapper.eq("gmt_create",begin);
        }
        if (!StringUtils.isEmpty(end)){
            wrapper.like("gmt_update",end);
        }
        wrapper.orderByDesc("gmt_create",begin);

        doctorService.page(page,wrapper);
        long total=page.getTotal();
        System.out.println(total);
        List<Doctor> records = page.getRecords();
        HashMap map = new HashMap();
        map.put("total",total);
        map.put("rows",records);
        return Result.succ().data(map);
    }


    @ApiOperation("添加医生")
    //添加医生的方法
    @PostMapping("addDoctor")
    public Result addDoctor(@RequestBody Doctor doctor){
        boolean save = doctorService.save(doctor);
        if (save){
            return Result.succ();
        }else {
            return Result.fail();
        }
    }

    @ApiOperation("根据医生的id进行查找返回，可用于医生信息进行回显修改")
    //根据id进行查询
    @GetMapping("GetDoctorById/{id}")
    public Result getDoctorById(@PathVariable String id){
        Doctor doctor = doctorService.getById(id);

        return Result.succ().data("doctor",doctor);
    }

    @ApiOperation("修改医生信息")
    @PostMapping("updateDoctor")
    public Result updateDoctor(@RequestBody Doctor doctor){
        boolean flag = doctorService.updateById(doctor);
        if (flag){
            return Result.succ();
        }else {
            return Result.fail();
        }
    }




}

